package rmmk.algorithms.similarityMeasures;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rmmk.algorithms.similarityMeasures.abstraction.AbstractSimilarityMeasure;
import rmmk.algorithms.similarityMeasures.utils.MostFrequentWords;
import rmmk.algorithms.similarityMeasures.utils.SpecifiedWordsFinder;
import rmmk.framework.datasources.Document;

public class TermFrequencyMatrix extends AbstractSimilarityMeasure {

	Logger logger = LoggerFactory.getLogger(TermFrequencyMatrix.class);
	double[][] termFrequencyMatrix;
	Double[] similarity = new Double[1];
	int limit;

	public TermFrequencyMatrix(int limit) {
		this.limit = limit;
	}

	@Override
	public Double[] doCalculate(Document input, Document document) {

		TreeMap<String, Integer> mostFrequentWords = MostFrequentWords
				.calculate(document, limit);
		TreeMap<String, Integer> foundWords = SpecifiedWordsFinder.calculate(
				input, mostFrequentWords);

		logger.debug("most freq");
		Iterator<Entry<String, Integer>> it = mostFrequentWords.entrySet()
				.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) it
					.next();
			logger.debug(pairs.getKey() + " = " + pairs.getValue());
		}

		logger.debug("input most freq");
		Iterator<Entry<String, Integer>> it2 = foundWords.entrySet().iterator();
		while (it2.hasNext()) {
			Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) it2
					.next();
			logger.debug(pairs.getKey() + " = " + pairs.getValue());
		}

		double upperPart = 0.0;
		double downPart = 0.0;
		double vector1 = 0.0;
		double vector2 = 0.0;

		Iterator<Entry<String, Integer>> it3 = mostFrequentWords.entrySet()
				.iterator();
		while (it3.hasNext()) {
			Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) it3
					.next();
			double found = foundWords.get(pairs.getKey());

			upperPart += pairs.getValue() * found;

			double value1 = pairs.getValue();
			double value2 = found;

			vector1 += value1 * value1;
			vector2 += value2 * value2;

		}

		downPart = Math.sqrt(vector1 * vector2);

		if (downPart == 0.0) {
			similarity[0] = 0.0;
		}
		similarity[0] = upperPart / downPart;

		logger.debug("similarity: " + similarity[0]);
		return similarity;
	}

	@Override
	public int getSimilarityMeasureSize() {
		return 1;
	}
}
